﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZkSurvey.BLL.SurveyMgr;
using ZkSurvey.Web.Helper;
using ZkSurvey.Common.SurveyMgr;
using ZkSurvey.Web.Helper.Extensions;
namespace ZkSurvey.Web.VP.SurveyMgr
{
    public partial class Edit : System.Web.UI.UserControl
    {
        QuestionBl questionBl = new QuestionBl();
        SurveyBl surveyBl = new SurveyBl();
        OptionBl optionBl = new OptionBl();
        DataDictionaryBl dicBl = new DataDictionaryBl();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                int? id = UrlHelper.GetQueryStringID();

                if (!id.HasValue)
                {
                    ErrorHelper.RaiseNoValueError();

                }
                else
                {
                    ViewState["SurveyId"] = id.Value;
                    Survey survey = surveyBl.GetSurvey(id.Value);
                    if (survey.Status == SurveyStatus.Running || survey.Status == SurveyStatus.Completed)
                    {
                        LBtnNewQuestion.Enabled = false;
                        GvList.Enabled = false;
                    }

                    LoadSurveyDetail();

                    BindQuestions();

                    ResetNewQuestionForm();

                    HlPreview.NavigateUrl = UrlHelper.GenerateUrl("SvDetail", "id", survey.Id.ToString());
                }
            }
            MessageHelper.Prepare(this.Page);
        }

        #region 问卷

        private void LoadSurveyDetail()
        {
            int id = Convert.ToInt32(ViewState["SurveyId"]);
            Survey survey = surveyBl.GetSurvey(id);

            tbxSurveyTitle.Text = survey.Title;
            tbxSurveyDescription.Text = survey.Description;
            tbxSurveyStartTime.Value = survey.StartTime.ToString("yyyy-MM-dd");
            tbxSurveyEndTime.Value = survey.EndTime.ToString("yyyy-MM-dd");
            tbxSurveyValidationCode.Text = survey.ValidationCode;
            tbxSurveyCreator.Text = survey.Creator;
            tbxSurveyCreatTime.Text = survey.CreateTime.ToString("yyyy-MM-dd");
            string url = string.Format("~/External/Submit.aspx?code={0}&vcode={1}", survey.Code, survey.ValidationCode);
            HlSurveyUrl.NavigateUrl = url;
            string fullUrl = Request.Url.AbsoluteUri.Substring(0, Request.Url.AbsoluteUri.LastIndexOf("/")) + ResolveUrl(url);
            HlSurveyUrl.Text = fullUrl;

            tbxStatus.Text = survey.StatusTitle;

            //HlSurveyUrl.NavigateUrl = UrlHelper.GenerateUrl("SvDetail", "id", id.ToString());
        }

        protected void BtnSaveEditSurvey_Click(object sender, EventArgs e)
        {
            int svId = Convert.ToInt32(ViewState["SurveyId"]);
            Survey survey = surveyBl.GetSurvey(svId);

            survey.Title = tbxSurveyTitle.Text.Trim();
            survey.Description = tbxSurveyDescription.Text.Trim();
            survey.StartTime = tbxSurveyStartTime.Date.Value;
            survey.EndTime = tbxSurveyEndTime.Date.Value;

            try
            {
                surveyBl.UpdateSurvey(survey);

                LoadSurveyDetail();

                if (survey.Status == SurveyStatus.Running || survey.Status == SurveyStatus.Completed)
                {
                    LBtnNewQuestion.Enabled = false;
                    GvList.Enabled = false;
                }
                else
                {
                    LBtnNewQuestion.Enabled = true;
                    GvList.Enabled = true;
                }

                MessageHelper.RegShowJSAjax(this.BtnSaveEditSurvey, "修改成功!", this.Page);
            }
            catch (ApplicationException ex)
            {
                MessageHelper.RegShowJSAjax(this.BtnSaveEditSurvey, ex.Message, this.Page);
            }

        }

        #endregion

        #region 数据绑定

        private void BindQuestions()
        {
            int id = Convert.ToInt32(ViewState["SurveyId"]);
            GvList.DataSource = questionBl.GetQuestionList(id);
            GvList.DataBind();
        }

        private void BindOption()
        {
            int quesId = Convert.ToInt32(ViewState["QuesId"]);

            gvOption.DataSource = optionBl.GetOptionList(quesId);
            gvOption.DataBind();
        }

        #endregion

        #region 问卷问题

        protected void BtnSaveNewQuestion_Click(object sender, EventArgs e)
        {
            int svId = Convert.ToInt32(ViewState["SurveyId"]);
            Question question = new Question();
            question.SurveyId = svId;
            question.Sort = Convert.ToInt32(tbxQuestionSort.Text.Trim());
            question.Type = (QuestionType)Convert.ToInt32(ddlQuesionType.SelectedValue);
            question.AllowInput = cbxAllowInput.Checked;
            question.Title = tbxQuestionTitle.Text.Trim();

            try
            {
                questionBl.CreateQuestion(question);
                BindQuestions();
                ResetNewQuestionForm();

                MessageHelper.RegShowJSAjax(this.BtnSaveNewQuestion, "添加成功", this.Page);
            }
            catch (ApplicationException ex)
            {

                MessageHelper.RegShowJSAjax(this.BtnSaveNewQuestion, ex.Message, this.Page);
            }
        }

        protected void BtnSaveEditQues_Click(object sender, EventArgs e)
        {
            int quesId = Convert.ToInt32(ViewState["QuesId"]);
            Question question = questionBl.GetQuestion(quesId);
            question.Sort = Convert.ToInt32(tbxEditQuesSort.Text.Trim());
            question.Title = tbxEditQuesTitle.Text.Trim();
            question.AllowInput = cbxEditQuesAllowInput.Checked;

            //保存每个单元格
            //TODO:检测用户输入
            foreach (GridViewRow gvRow in gvOption.Rows)
            {
                Option opt = new Option();
                opt.Id = Convert.ToInt32(gvOption.DataKeys[gvRow.RowIndex].Value);
                opt.QuestionId = quesId;
                opt.Sort = Convert.ToInt32(((TextBox)gvRow.FindControl("tbxOptSort")).Text);
                opt.Value = ((TextBox)gvRow.FindControl("tbxOptValue")).Text;
                opt.Name = ((TextBox)gvRow.FindControl("tbxOptTitle")).Text;
                question.Options.Add(opt);
            }

            try
            {
                questionBl.UpdateQuestion(question);
                BindQuestions();
                MessageHelper.RegShowJSAjax(this.GvList, "修改问题成功", this.Page);
            }
            catch (ApplicationException ex)
            {
                MessageHelper.RegShowJSAjax(this.GvList, ex.Message, this.Page);
            }

        }

        protected void GvList_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            //编辑问题
            if (e.CommandName == "EditQues")
            {
                int quesId = Convert.ToInt32(e.CommandArgument);
                ViewState["QuesId"] = quesId;

                Question question = questionBl.GetQuestion(quesId);
                tbxEditQuesSort.Text = question.Sort.ToString();
                lblEditQuesType.Text = question.TypeTitle;
                tbxEditQuesTitle.Text = question.Title;
                cbxEditQuesAllowInput.Checked = question.AllowInput;

                if (question.Type != QuestionType.Input)
                {
                    divEditOptions.Visible = true;
                    divEditQuesAllowInput.Visible = true;
                    BindOption();
                }
                else
                {
                    divEditOptions.Visible = false;
                    divEditQuesAllowInput.Visible = false;
                }

                mpeEditQues.Show();
            }
            //删除问题
            else if (e.CommandName == "DeleteQues")
            {
                int quesId = Convert.ToInt32(e.CommandArgument);
                try
                {
                    questionBl.DeleteQuestion(quesId);
                    BindQuestions();
                    MessageHelper.RegShowJSAjax(this.GvList, "删除问题成功!", this.Page);
                }
                catch (ApplicationException ex)
                {
                    MessageHelper.RegShowJSAjax(this.GvList, ex.Message, this.Page);
                }
            }
        }

        protected void GvList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Question question = e.Row.DataItem as Question;
                if (question.Type != QuestionType.Input)
                {
                    Repeater rptOptions = e.Row.FindControl("rptOptions") as Repeater;
                    rptOptions.DataSource = question.Options;
                    rptOptions.DataBind();
                }
                else
                {
                    e.Row.Cells[3].Text = "----------";
                }
            }
        }

        protected void GvList_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.GvList.PageIndex = e.NewPageIndex;
            BindQuestions();
        }

        private void ResetNewQuestionForm()
        {
            int surveyId = Convert.ToInt32(ViewState["SurveyId"]);
            ddlQuesionType.DataSource = new DataDictionaryBl().GetQuestionTypes();
            ddlQuesionType.DataTextField = "Title";
            ddlQuesionType.DataValueField = "Id";
            ddlQuesionType.DataBind();

            tbxQuestionTitle.Text = string.Empty;
            cbxAllowInput.Checked = false;
            tbxQuestionSort.Text = questionBl.GetNextSort(surveyId).ToString();
        }

        #endregion

        #region 选项

        protected void gvOption_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "DeleteOpt")
            {
                int optId = Convert.ToInt32(e.CommandArgument);
                optionBl.DeleteOption(optId);
                BindOption();
                mpeEditQues.Show();
            }
        }

        protected void LbtnNewOption_Click(object sender, EventArgs e)
        {
            ResetNewOptionForm();
            mpeNewOption.Show();
        }

        protected void BtnCancelNewOpt_Click(object sender, EventArgs e)
        {
            mpeEditQues.Show();

        }

        protected void BtnSaveNewOpt_Click(object sender, EventArgs e)
        {
            int quesId = Convert.ToInt32(ViewState["QuesId"]);

            Option opt = new Option();
            opt.QuestionId = quesId;
            opt.Name = tbxNewOptName.Text.Trim();
            opt.Value = tbxNewOptValue.Text.Trim();
            opt.Sort = Convert.ToInt32(tbxNewOptSort.Text.Trim());

            optionBl.CreateOption(opt);
            BindOption();

            mpeEditQues.Show();
        }

        private void ResetNewOptionForm()
        {
            int quesId = Convert.ToInt32(ViewState["QuesId"]);

            tbxNewOptName.Text = string.Empty;
            tbxNewOptValue.Text = string.Empty;
            tbxNewOptSort.Text = optionBl.GetNextSort(quesId).ToString();
        }

        #endregion
    }
}